<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<meta name="decorator" content="default"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Cache-Control" content="no-store">

<meta http-equiv="pragma" content="no-cache"  />
<meta http-equiv="content-type" content="no-cache, must-revalidate" />
<meta http-equiv="expires" content="0"/>

<title>upload</title><script src="${ctxStatic}/jquery/jquery-1.8.3.min.js" type="text/javascript"></script>
<link href="${ctxStatic}/file-tool/uploadify/upload/system.css" rel="stylesheet" type="text/css" />
<script  src="${ctxStatic}/file-tool/uploadify/upload/system.js" type="text/javascript"></script>
<link href="${ctxStatic}/file-tool/uploadify/3.2.1/uploadify.css" rel="stylesheet" type="text/css" />
<script src="${ctxStatic}/file-tool/uploadify/3.2.1/jquery.uploadify.js" type="text/javascript" ></script>

<script type="text/javascript">
var uploadAction = "${ctxStatic}/file/connector;JSESSIONID=${pageContext.session.id}";//;JSESSIONID=${pageContext.session.id}
var fileId = '${param.fileId}'; 
var dialogId = '${param.dialogId}';
var targetId = '${param.targetId}';
var callback = '${param.callback}';
var serverType = '${param.serverType}';
var isMulti = '${param.isMulti}';
var fileSize = eval('${param.fileSize}');
var command = '${param.command}';

var lessonSn = '${param.lessonSn}';
var hasCheckSn = '${param.hasCheckSn}';

var isAuto = true;
var fileTypeDesc = "文件";
//var fileTypeExts = null;//
var fileTypeExts = '${param.fileType}';
var currentFilePath = '${param.uploadPath}';
var uid = '${param.uid}';
var stopQueue= {};

function startUpload(){
	jQuery('#uploadify').uploadify('upload','*');
}
function cancel(){
	jQuery('#uploadify').uploadify('cancel','*');
	//jQuery('#'+dialogId,parent.document).remove();
	parent.closeWindows(dialogId)
}

function init(){
	if(currentFilePath == null){
		currentFilePath = '/test';
	}
	var date = new Date(), year = date.getFullYear(), month = (date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1);
	var currentFolder = currentFilePath+"/"+year+"/"+month+"/";
	var filetype = null;
	if(filetype == null){
		filetype = 'files';
	}
	
	if(uid == null || uid == ''){
		uid = 'file'+Math.round(Math.random()*Math.pow(10,10));
	}
	if(isMulti == null || isMulti == ''){
		isMulti = false;
	}
	if(fileTypeExts == ''){
		fileTypeExts = '*.*';
	}
	uploadAction = addUrlParam(uploadAction,'type',filetype);
	uploadAction = addUrlParam(uploadAction,'currentFolder',currentFolder);
	uploadAction = addUrlParam(uploadAction,'langCode','zh-cn');
	uploadAction = addUrlParam(uploadAction,'prefix',currentFolder);
	
	if(fileSize == null || fileSize == ''){
		fileSize = 1024*500;
	}
	if(command == null|| command == ''){
		command = 'FileUpload';
	}
	//var fileSize = Math.round(settings.fileSizeLimit / 1024)*1024;
	var suffix   = 'KB';
	var size = Math.round(fileSize*1000 / 1024);
	if (size > 1000) {
		size = Math.round(size / 1000);
		suffix   = 'MB';
	}
	var fileSizeParts = size.toString().split('.');
	var showFileSize = fileSizeParts[0];
	if (fileSizeParts.length > 1) {
		showFileSize += '.' + fileSizeParts[1].substr(0,2);
	}
	showFileSize += suffix;
	var info = '最大尺寸'+showFileSize;
	jQuery('#filesizeid').html(info);
	if(isAuto){
		jQuery('[name="uploadButton"]').css('display','none');
	}
}

</script>

<script type="text/javascript">
	$(function() { 
		init(); //debugger;
		var script= uploadAction ;
		script = addUrlParam(script,'command',command);
		//script = addUrlParam(script,'uid',uid);
		script = addUrlParam(script,'serverType',serverType);
		var formData = {};
		var percentagecount = 0;
        $("#uploadify").uploadify({
           	// Required Settings
            'swf': '${ctxStatic}/file-tool/uploadify/3.2.1/uploadify.swf',
            'uploader': script,
			
			// Options
			auto            : isAuto,              // Automatically upload files when added to the queue
			buttonClass     : '',                 // A class name to add to the browse button DOM object
			buttonCursor    : 'hand',             // The cursor to use with the browse button
			buttonImage     : null,                 // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
			buttonText      : 'SELECT',           // The text to use for the browse button
			checkExisting   : false,              // The path to a server-side script that checks for existing files on the server
			debug           : false,              // Turn on swfUpload debugging mode
			fileObjName     : 'Filedata',         // The name of the file object to use in your server-side script
			fileSizeLimit   : fileSize,                  // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
			fileTypeDesc    : fileTypeDesc==null?'All File' :  fileTypeDesc,        // The description for file types in the browse dialog
			fileTypeExts    : fileTypeExts==null?"*.*": fileTypeExts,              // Allowed extensions in the browse dialog (server-side validation should also be used)
			height          : 30,                 // The height of the browse button
			itemTemplate    : false,              // The template for the file item in the queue
			method          : 'post',             // The method to use when sending files to the server-side upload script
			multi           : isMulti,               // Allow multiple file selection in the browse dialog
			formData        : formData,                 // An object with additional data to send to the server-side upload script with every file upload
			preventCaching  : true,               // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
			progressData    : 'percentage',       // ('percentage' or 'speed') Data to show in the queue item during a file upload
			queueID         : 'uploadifyqueue',              // The ID of the DOM object to use as a file queue (without the #)
			queueSizeLimit  : 5,                // The maximum number of files that can be in the queue at one time
			removeCompleted : false,               // Remove queue items from the queue when they are done uploading
			removeTimeout   : 30000,                  // The delay in seconds before removing a queue item if removeCompleted is set to true
			requeueErrors   : false,              // Keep errored files in the queue and keep trying to upload them
			successTimeout  : 600000,                 // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
			uploadLimit     : 5,                  // The maximum number of files you can upload
			width           : 80,                // The width of the browse button
            onCancel : function(file) {
         			 //alert('The file ' + file.name + ' was cancelled.');
    		},
    		//this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize
       		onUploadProgress: function(file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded,uploadSize){ //
       			var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
       			var html = null;
       			if(percentage == 0){
       				html = '<div class="righttag">正在加载...</div>';
       			}else{
       				html ='<div class="righttag">正在加载'+percentage+'%</div>';
       			}
       			$('#' + file.id).find('.data').html(html);
       		},
			onUploadSuccess : function(file, data, response){
				if(file!=null){
					var key = uid+file.id;
					stopQueue[key] = true;
				}
				if(data==null){
					return false;
				}
    			var fileObj = jQuery('#'+file.id);
    			setFinish(fileObj);
    			var json = eval('('+data+')');
    			callbackFunction(json.uid);
    			//cancel(); //关闭窗口
			},
			onQueueComplete : function(data){
				if(data!=null&&data.uploadsErrored == 0){
					cancel(); //关闭窗口
				}
			},
			onUploadStart : function(file){
				if(file!=null){
					if(lessonSn!=null && hasCheckSn != null && ( hasCheckSn == "1" || hasCheckSn == true) ){
						var name = file.name;
						var sn = name;
						var ext = "";
						if(name.indexOf(".")>-1 ){
							sn = name.substr(0,name.indexOf("."));
							ext= name.substr(name.indexOf("."));
						}
						//debugger;
						if(lessonSn != sn){
							alert("文件名【"+file.name+"】和课程编号【"+lessonSn+"】不一致,请检查课件上传是否正确  ,  课件必须为【"+lessonSn+ext+"】");
		       				cancel(); //关闭窗口
		       				return ;
						}
					}
					
					
					var fileUid = uid+file.id;
					stopQueue[fileUid] = false;
					$("#uploadify").uploadify("settings", "formData", { 'uid': fileUid }); 
					
				}
			}
			,onUploadError : function(file, errorCode, errorMsg,errorString){}
			,overrideEvents  : ['onUploadProgress','onUploadSuccess']
          });
      });  
	
	function setFinish(fileObj){
		var cancelObj = fileObj.children('.cancel');
		fileObj.children('.data').html('--已完成');
		cancelObj.html('<a ></a>');
		var aObj = cancelObj.children('a');
		aObj.css('background-image','none');
		aObj.css('text-indent','-30px');
		aObj.css('width','50px');
		fileObj.find('.uploadify-progress-bar').css('width', 100 + '%');
	}
	
	function callbackFunction(fileUid){
		var functionName = "parent."+callback+"('"+fileUid+"')";
		eval(functionName);
	}
	function loadReed(id){
		var fileUid = uid+id;
		if(stopQueue[fileUid] == true){
			return ;
		}
		var data = {uid : fileUid,command : 'GetProgress',serverType : serverType};
		var urls = uploadAction;
		jQuery.ajax({  
			url: urls, async : true,type: "POST",dataType : 'json',
			data : data,
			success: function(response) {
				var info = response;
				var percentage = info.percentage;
				var fileObj =  $('#' + id);
				var progress = fileObj.find('.uploadify-progress-bar');
				if(percentage<100){
					if(0 == percentage){
						//fileObj.find('.data').html('<div class="righttag">正在加载...</div>');
						//fileObj.find('.data').html('开始上传');
					}else{
						fileObj.find('.data').html(' - ' + percentage + '%');
						progress.css('width', percentage + '%');
					}
					setTimeout('loadReed("'+id+'")', 1000);
				}else if(percentage == 100){
					stopQueue[fileUid] = true;
					setFinish(fileObj);
					callbackFunction(json.uid);
				}
			},
			error: function(e){console.error(e);}
		});
	}
	
  </script>
  <style type="text/css">
  	.righttag{
		  top: 5px;
		  right: 10px;
		  width: 100px;
		  height: 20px;
		  line-height: 20px;
		  background: #f8f8f8 url(smallloader.gif) no-repeat 8px center;
		  border: 1px solid #ddd;
		  padding-left: 30px;
		  font-size: 11px;
		  color: #888;
		  z-index: 9999;
  	}
  	.uploadListDiv{
  		height: 180px;
  	}
  	.uploadList{
  		height: 180px;
  	}
  </style>
  
</head>
<body>
<!-- <input type="button" name="getUploadButton" value="获取文件信息" onclick="getFileinfo()">
 -->
	<div class="uploadDiv" style="height: 270px;">
		<!-- 文件上传Table  -->
		<table class="uploadTable" style="height: 240px;">
			<!-- 标题区域 -->
			<tr class="uploadTitle" style="height: 40px;">
				<td colspan="3">
					<div class="uploadTitleDiv" style="text-align: left;font-size: 11px;line-height:26px;height: 26px;padding-left: 10px;">
						<span id="filesizeid"></span>
						<!-- 附件上传 
						jQuery插件版本 ： uploadfy3.2.1-->
					</div>
				</td>
			</tr>
			<!-- 文件区域 -->
			<tr class="uploadList">
				<td colspan="3">
					<div class="uploadListDiv" id="uploadifyqueue" style="background-color: #FFFFFF;">
						
					</div>
				</td>
			</tr>
			<!-- 按钮区域 -->
			<tr class="uploadButton">
				<td class="uploadButtonleft">
					<div class="uploadButtonImg">
						<!-- <input type="button" value="选择文件"> -->
						<input type="file" name="uploadify" id="uploadify"/>
					</div>
				</td>
				<td class="uploadButtonCenter">
					<input type="button" name="uploadButton" value="上传" onclick="startUpload()">
				</td>
				<td class="uploadButtonRight">
					<input type="button"  value="关闭" onclick="cancel()">
					<!-- <input type="button" value="获取文件" onclick="getFileinfo()"> -->
				</td>
			</tr>
		</table>
	</div>

</body>
</html>
